<?php

//观察者模式
class user implements SplSubject{
	//数据定义
	public $lognum;
	public $hobby;
	//结束数据定义
	private $observers = null;

	public  function login($hobby){
		$this->hobby = $hobby;
		$this->notify();
	}

	public function __construct($hobby){
		// todo
		$this->lognum = rand(1,10);
		$this->hobby = $hobby;
		// end todo
		$this->observers = new SplObjectStorage();
	}

	public function attach(SPLObserver $observer){
		$this->observers->attach($observer);
	}

	public function detach(SPLObserver $observer) {
		$this->observers->detach($observer);	
	}

	public function notify() {
		$this->observers->rewind();
		while ($this->observers->valid()) {
			$observer = $this->observers->current();
			$observer->update($this);
			$this->observers->next();
		}
	}

}

class sec implements SPLObserver {
	public function update(SPLSubject $subject){
		if ($subject->lognum <3) {
			echo $subject->lognum, 'safe';
		}  else {
			echo $subject->lognum, 'dange';
		}
	}
}

class ad implements SPLObserver {
	public function update(SPLSubject $subject){
		if ($subject->hobby == 'sport') {
			echo 'sport';
		}  else {
			echo 'good';
		}
	}
}

$user = new user('sport');
$user->attach(new sec());
$user->attach(new ad());

$user->login('sport');

?>